<template>
  <div>
    <!-- 返回 -->
    <ReturnPage />

    <el-card class="mt10 mb10">
      <!-- <div slot="header" class="clearfix"> -->
      <!-- <h2 class="mb20">{{ hostDetail.Inner_IP }}</h2> -->
      <!-- temporary -->
      <!-- <el-button style="float: right; padding: 3px 0" type="text"
          >修改</el-button
        > -->
      <!--  </div> -->
      <div class="tab_box">
        <template>
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <!-- 主机属性 -->
            <el-tab-pane label="主机属性" name="first">
              <!-- 基础信息 -->
              <div class="only_name" v-if="getExampleObj.length == 0">
                实例名:
                <!-- 属性值 -->
                <div class="value_box">
                  &nbsp;&nbsp;{{ hostDetail.model_example_name }}
                  <svg-icon iconClass="icon-edit" class="editBtn" style="margin-left: 5px"
                    @click="activeExample = hostDetail.model_example_name"></svg-icon>
                </div>
                <!-- 输入框 -->
                <div class="input_box" :class="{
                  active: activeExample == hostDetail.model_example_name,
                }">
                  <el-input size="mini" v-model="form.input"
                    :placeholder="'请输入' + hostDetail.model_example_name"></el-input>

                  <el-button icon="el-icon-check" size="mini" circle style="margin-left: 10px"
                    @click="editExample('model_example_name')"></el-button>
                  <el-button icon="el-icon-close" size="mini" circle @click="activeExample = ''"></el-button>
                </div>
              </div>
              <div v-else v-for="(item, index) in getExampleObj" :key="index">
                <p style="
                    padding-left: 10px;
                    border-left: 5px solid #c3cdd7;
                    font-weight: 550;
                  ">
                  {{ item.categoryName }}
                </p>
                <div class="stats mb20">
                  <div class="property" v-for="ele in item.children" :key="ele.modelFieldId">
                    <div class="comment_box">
                      {{ ele.comment }}:
                      <!-- 属性值 -->
                      <div class="value_box">
                        &nbsp;&nbsp;{{ ele.value }}
                        <svg-icon iconClass="icon-edit" class="editBtn" style="margin-left: 5px" @click="
                          activeExample = ele.newFieldName; form.input = ele.value
                          "></svg-icon>
                      </div>
                      <!-- 输入框 -->
                      <div class="input_box" v-if="activeExample == ele.newFieldName">
                        <!-- <el-date-picker v-if="ele.type == 'DATE'" v-model="input" type="date"
                          :placeholder="'请选择' + ele.comment" value-format="yyyy-MM-dd">
                        </el-date-picker>

                        <el-date-picker v-else-if="ele.type == 'DATETIME'" v-model="input" type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss" :placeholder="'请选择' + ele.comment">
                        </el-date-picker> -->
                        <el-form :model="form" ref="form">
                          <el-form-item prop="input" :rules="rules[ele.newFieldName]">
                            <el-input size="mini" v-model="form.input" :placeholder="'请输入' + ele.comment"></el-input>
                            <el-button icon="el-icon-check" size="mini" circle style="margin-left: 10px"
                              @click="editExample('form', ele.newFieldName)"></el-button>
                            <el-button icon="el-icon-close" size="mini" circle @click="activeExample = ''"></el-button>
                          </el-form-item>
                        </el-form>
                        <!-- <el-input size="mini" v-model="input" :placeholder="'请输入' + ele.comment"></el-input>
                        <el-button icon="el-icon-check" size="mini" circle style="margin-left: 10px"
                          @click="editExample(ele.newFieldName)"></el-button>
                        <el-button icon="el-icon-close" size="mini" circle @click="activeExample = ''"></el-button> -->
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </el-tab-pane>

            <!-- 服务列表 -->
            <el-tab-pane label="服务列表" name="second">
              <el-table :data="tableData" style="width: 100%" height="calc(100vh - 400px)">
                <el-table-column prop="serviceProcessName" label="进程名称">
                </el-table-column>
                <el-table-column prop="serviceProcessAlias" label="进程别名">
                </el-table-column>
                <el-table-column prop="serviceProcessParameter" label="进程启动参数">
                </el-table-column>
                <el-table-column prop="serviceProcessBinding" label="进程绑定信息">
                </el-table-column>
                <el-table-column prop="updateTime" label="修改时间">
                </el-table-column>
                <el-table-column label="操作" width="80">
                  <template slot-scope="scope">
                    <el-button size="mini" type="primary" @click="showEditProcess(scope.row)">编辑</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <pagination v-show="total > 0" :total="total" :page.sync="query.pageNum" :limit.sync="query.pageSize"
                :select-data-len="multipleSelection.length" @pagination="getProcessListByHostId" />
            </el-tab-pane>

            <!-- 关联 -->
            <!-- <el-tab-pane label="关联" name="third">
              <div style="display: flex; justify-content: space-between">
                <el-button type="primary" plain>新增关联</el-button>
                <div>
                  <el-checkbox v-model="checked">全部展开</el-checkbox>
                  <el-radio-group
                    v-model="activeRadio"
                    style="margin-left: 15px"
                  >
                    <el-radio-button label="列表">列表</el-radio-button>
                    <el-radio-button label="拓扑">拓扑</el-radio-button>
                  </el-radio-group>
                </div>
              </div>
            </el-tab-pane> -->

            <!-- 变更记录 -->
            <!-- temporary -->
            <!-- <el-tab-pane label="变更记录" name="fourth">
              <el-date-picker
                style="margin-bottom: 20px"
                v-model="value1"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
              <el-table :data="alterationTableData" style="width: 100%" border>
                <el-table-column prop="desc" label="操作描述">
                </el-table-column>
                <el-table-column prop="account" label="操作账号">
                </el-table-column>
                <el-table-column prop="date" label="操作日期">
                </el-table-column>
              </el-table>
            </el-tab-pane> -->
          </el-tabs>
        </template>
      </div>
    </el-card>

    <!-- 编辑进程弹窗 -->
    <el-dialog title="编辑进程" :visible.sync="editProcessVisible">
      <el-form ref="editProcessForm" :model="editProcessForm" :rules="rules" label-width="100px">
        <el-form-item label="进程名称" prop="serviceProcessName">
          <el-input v-model="editProcessForm.serviceProcessName" placeholder="请输入进程名称"></el-input>
        </el-form-item>
        <el-form-item label="进程别名" prop="serviceProcessAlias">
          <el-input v-model="editProcessForm.serviceProcessAlias" placeholder="请输入进程别名"></el-input>
        </el-form-item>
        <el-form-item label="进程启动参数" prop="serviceProcessParameter">
          <el-input v-model="editProcessForm.serviceProcessParameter" placeholder="请输入进程启动参数"></el-input>
        </el-form-item>
        <el-form-item label="进程绑定信息" prop="serviceProcessParameter">
          <el-input v-model="editProcessForm.serviceProcessBinding" placeholder="请输入进程绑定信息"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="editProcess('editProcessForm')">确定</el-button>
        <el-button @click="editProcessVisible = false" size="mini">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
let queryIp = (rule, value, callback) => {
  const ipv4Regex =
    /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?::[0-9]{1,5})?$/;
  if (!ipv4Regex.test(value)) {
    callback(new Error("ip格式错误"));
  } else {
    callback();
  }
};
import {
  getModelExampleDetail_Api, //根据实例id查询实例详情
  getModelIdCategoryList_Api, //根据模型id查询模型分组列表
  editModelExample_Api, //编辑模型实例
} from "@/api/configuration/resource";
import {
  getProcessListByHostId_Api, //根据主机id查询进程列表
  editProcess_Api, //编辑进程
} from "@/api/configuration/business.js";
import {
  getCurrent_YMDHMS_Time, //获取当前年月日时分表
} from "@/utils/common.js";
export default {
  data() {
    return {
      rules: {
        model_example_name: [
          { required: true, message: `请输入实例名`, trigger: "blur" },
        ],
      },
      activeExample: "", //选中的字段
      form: {
        input: "", //编辑字段输入的值
      },
      editProcessVisible: false, //控制编辑进程弹框显示隐藏
      editProcessForm: {}, //编辑进程表单
      checked: false, //全部展开选择框
      activeRadio: "列表", //选中的radio
      value1: "",
      // 数据条数
      total: 0,
      //分页数据
      query: {
        pageNum: 1,
        pageSize: 10,
      },
      multipleSelection: [],
      alterationTableData: [
        {
          desc: "新增实例",
          account: "admin",
          date: "2022.9.1",
        },
        {
          desc: "新增实例",
          account: "admin",
          date: "2022.9.1",
        },
      ],
      //服务列表
      tableData: [],
      activeName: "first",
      //主机详情
      hostDetail: {},
      //实例属性字段
      exampleFields: [],
    };
  },
  created() {
    this.getModelExampleDetail(); //根据实例id获取实例详情
    this.getProcessListByHostId(); //根据主机id查询进程列表
  },
  methods: {
    //根据实例id获取实例详情
    getModelExampleDetail() {
      getModelExampleDetail_Api(this.$route.query.id).then((res) => {
        this.hostDetail = res.data[0];
        this.getExampleFields(this.hostDetail.model_id); //根据modelId获取实例详情字段信息
      });
    },
    //根据modelId获取实例详情字段信息
    getExampleFields(id) {
      //查询字段
      getModelIdCategoryList_Api({ modelId: id }).then((res) => {
        this.exampleFields = res.data;
      });
    },
    //根据主机id查询进程列表
    getProcessListByHostId() {
      getProcessListByHostId_Api(this.query, this.$route.query.id).then(
        (res) => {
          this.tableData = res.rows;
          this.total = res.total;
        }
      );
    },
    //编辑进程
    editProcess() {
      this.editProcessForm.updateTime = getCurrent_YMDHMS_Time();
      editProcess_Api(this.editProcessForm)
        .then((res) => {
          this.$message.success(res.msg);
          this.editProcessVisible = false;
          this.getProcessListByHostId();
        })
        .catch((error) => { });
    },
    //显示编辑进程弹框
    showEditProcess(row) {
      this.editProcessForm = {
        serviceProcessId: row.serviceProcessId,
        serviceProcessAlias: row.serviceProcessAlias,
        serviceProcessBinding: row.serviceProcessBinding,
        serviceProcessName: row.serviceProcessName,
        serviceProcessParameter: row.serviceProcessParameter,
        serviceTemplateId: row.serviceTemplateId,
      };
      this.editProcessVisible = true;
    },
    //编辑模型实例的方法
    //必选参数：实例id + 模型id + （要修改的字段（newFieldName）和新值）
    editExample(formName, newFieldName) {
      this.$refs[formName][0].validate((valid) => {
        if (valid) {
          if (this.form.input != "") {
            editModelExample_Api({
              // modelId: this.hostDetail.model_id,
              // modelExampleId: this.hostDetail.model_example_id,
              ...this.hostDetail,
              [newFieldName]: this.form.input,
            })
              .then((res) => {
                this.getModelExampleDetail(this.hostDetail.model_example_id);
                this.$message.success("修改成功");
                this.activeExample = "";
                this.form.input = "";
              })
              .catch((error) => { });
          } else this.$message.info("输入不能为空");
        } else {
          console.log('error submit!!');
          return false;
        }
      });

    },
    handleClick(tab, event) {
      // console.log(tab, event);
    },
  },
  computed: {
    getExampleObj() {
      const tempArr = [];
      this.exampleFields.forEach((item) => {
        const tempCategoryObj = {};
        tempCategoryObj.categoryName = item.categoryName;
        tempCategoryObj.children = [];
        item.cgModelFields.forEach((ele) => {
          //每个字段对象
          const tempObj = {};
          tempObj.type = ele.type;
          tempObj.comment = ele.comment;
          if (ele.testingRegulationsJSON) {
            let arr = []
            JSON.parse(ele.testingRegulationsJSON).forEach(e => {
              let obj = {}
              switch (e.type) {
                case "max":
                  obj.max = Number(e.val)
                  obj.trigger = e.trigger
                  obj.message = e.message
                  break;
                case "min":
                  obj.min = Number(e.val)
                  obj.trigger = e.trigger
                  obj.message = e.message
                  break;
                case "number":
                  obj.type = e.type
                  obj.trigger = e.trigger
                  obj.message = e.message
                  break;
                case "string":
                  obj.type = e.type
                  obj.trigger = e.trigger
                  obj.message = e.message
                  break;
                case "ip":
                  obj.validator = queryIp
                  obj.trigger = e.trigger
                  break;
                case "email":
                  obj.type = e.type
                  obj.trigger = e.trigger
                  obj.message = e.message
                  break;
                case "required":
                  obj.required = true
                  obj.trigger = e.trigger
                  obj.message = e.message
                  break;
                default:
                  break;
              }
              arr.push(obj)
            })
            this.rules[ele.newFieldName] = arr
            console.log(this.rules);
          }
          tempObj.value = this.hostDetail[ele.newFieldName];
          tempObj.edit_box_visible = false; //控制编辑输入框显示隐藏
          //把驼峰命名转化为下划线隔开
          // const newFieldName = ele.newFieldName
          //   .replace(/([a-z])([A-Z])/g, "$1_$2")
          //   .toLowerCase();
          // tempObj.newFieldName = newFieldName;
          tempObj.newFieldName = ele.newFieldName;
          tempCategoryObj.children.push(tempObj);
        });
        if (tempArr.length == 0) {
          tempCategoryObj.children.unshift({
            comment: "实例名",
            value: this.hostDetail.model_example_name,
            edit_box_visible: false,
            newFieldName: "model_example_name",
          });
        }
        tempArr.push(tempCategoryObj);
      });
      return tempArr;
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-tab-pane {
  height: calc(100vh - 80px);
}

::v-deep .el-tabs__content {
  padding-bottom: 10px;
}

.tab_box {

  //只有实例名没有分组等信息时
  .only_name {
    margin-top: 20px;
    width: 200px;
    text-align: right;
    position: relative;

    .input_box {
      white-space: nowrap;
      position: absolute;
      left: 200px;
      top: -4px;
      margin-left: 5px;
      width: 200px;
      margin-right: 10px;
      z-index: 3;
      // display: none;

      &.active {
        display: block;
      }
    }

    .value_box {
      text-align: left;
      width: 350px;
      position: absolute;
      left: 200px;
      top: 2px;
      z-index: 2;
    }
  }

  //属性
  .stats {
    margin-top: 10px;
    font-size: 12px;
    display: grid;
    grid-template-columns: 48% 52%;
    gap: 20px 15px;

    .property {
      .comment_box {
        width: 200px;
        text-align: right;
        position: relative;

        .input_box {
          white-space: nowrap;
          position: absolute;
          left: 200px;
          top: -5px;
          margin-left: 5px;
          width: 200px;
          margin-right: 10px;
          z-index: 3;
          // display: none;

          &.active {
            display: block;
          }
        }

        .value_box {
          text-align: left;
          width: 350px;
          position: absolute;
          left: 200px;
          top: 0px;
          z-index: 2;
        }
      }

      &:hover .editBtn {
        display: inline-block;
        cursor: pointer;
        color: #72767c;

        &:hover {
          color: #409eff;
        }
      }

      .editBtn {
        display: none;
      }
    }
  }
}
</style>
